package com.bill99.golden.inf.sso.client;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.bill99.golden.inf.sso.mdp.dto.RefreshTokenTimeRequestDto;

public class RefreshSSOThread extends Thread {
	static Map<String, RefreshTokenTimeRequestDto> ssoMap = new HashMap<String, RefreshTokenTimeRequestDto>();
	static Object lock = new Object();
	static boolean isRun = false;
	static final long waitTime = 1000 * 90;
	private IssoClient ssoClient;

	public RefreshSSOThread(IssoClient ssoClient) {
		this.ssoClient = ssoClient;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		isRun = true;
		try {
			Thread.sleep(waitTime);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		isRun = false;
		Map<String, RefreshTokenTimeRequestDto> sm = new HashMap<String, RefreshTokenTimeRequestDto>();
		synchronized (lock) {
			sm.putAll(ssoMap);
			ssoMap.clear();
		}
		Iterator<RefreshTokenTimeRequestDto> it = sm.values().iterator();
		while (it.hasNext()) {
			RefreshTokenTimeRequestDto r = (RefreshTokenTimeRequestDto) it
					.next();
			try {
				long timeSpan = System.currentTimeMillis()
						- r.getVisitTimeSpan().longValue();
				r.setVisitTimeSpan(new Long(timeSpan));
				ssoClient.refreshTokenTime(r);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		sm.clear();
	}

	public static void refreshSSOTime(IssoClient ssoClient,
			HttpServletRequest request, String token, String appCode) {
		if (token == null)
			return;
		synchronized (lock) {
			RefreshTokenTimeRequestDto rtr = ssoMap.get(token);
			if (rtr == null) {
				String explorerType = request.getHeader("user-agent");
				String userIp = request.getRemoteHost();
				RefreshTokenTimeRequestDto r = new RefreshTokenTimeRequestDto();
				r.setAppCode(appCode);
				r.setUserIp(userIp);
				r.setExplorerType(explorerType);
				r.setToken(token);
				r.setVisitTimeSpan(new Long(System.currentTimeMillis()));
				ssoMap.put(token, r);
			} else {
				rtr.setVisitTimeSpan(new Long(System.currentTimeMillis()));
			}
		}
		if (isRun == false) {
			RefreshSSOThread t = new RefreshSSOThread(ssoClient);
			t.start();
		}
	}
}
